import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as OutResourceViewAction from '../../actions/outResource'

import { WeaTable } from 'comsRedux'

const WeaTableAction = WeaTable.action;

import {
    WeaTab,
    WeaLeftTree,
    WeaLeftRightLayout,
    WeaSearchGroup,
    WeaRightMenu,
    WeaPopoverHrm
} from 'ecCom'

import {WeaErrorPage,WeaTools} from 'ecCom'
const { getComponent } = WeaTools;

import {Button,Form,Modal,message} from 'antd' 
const createForm = Form.create;
const FormItem = Form.Item;

import Immutable from 'immutable'
const is = Immutable.is;

let _this = null;

class OutResourceList extends React.Component {
    constructor(props) {
		super(props);
        _this = this;
        this.state={
            required:[]
        }
    }
    componentDidMount() {
    	 const {actions,location:{query}} = this.props;
        actions.getOutResourceList(query);
    }
    componentWillReceiveProps(nextProps) {

    }
    shouldComponentUpdate(nextProps,nextState) {
        return !is(this.props.dataKey,nextProps.dataKey)||
        !is(this.props.comsWeaTable,nextProps.comsWeaTable)||
        !is(this.props.customerId,nextProps.customerId)||
        !is(this.props.addFormDatas,nextProps.addFormDatas)||
        !is(this.props.showAddForm,nextProps.showAddForm)||
        !is(this.props.outResourceOrderFields,nextProps.outResourceOrderFields)||
        !is(this.props.outResourceParams,nextProps.outResourceParams)
    }
    componentWillUnmount(){

    }
    render() {
        const {dataKey,comsWeaTable,showAddForm} = this.props;
        return (
            <div className="height100">
                <WeaRightMenu datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)}>
                    {
                        !showAddForm && 
                        <WeaTable 
                            sessionkey={dataKey}
                            hasOrder={true}
                            needScroll={true}
                        />
                    }
                    {
                        showAddForm && 
                        <Form horizontal>{this.getForm()}</Form>
                    }
                </WeaRightMenu>
            </div>
        )
    }
    getRightMenu(){
        const {showAddForm,dataKey,comsWeaTable} =this.props;
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
        let btns = [];
        {
            !showAddForm &&
            btns.push({
                icon: <i className='icon-coms-New-Flow'/>,
                content:'新建',
                key:0
            });
        }
        {  
            !showAddForm &&
            btns.push({
                icon: <i className='icon-coms-delete'/>,
                content:'删除',
                key:1,
                disabled: !selectedRowKeys || !`${selectedRowKeys.toJS()}`
            });
        }
        {   
            !showAddForm &&
                btns.push({
                icon: <i className='icon-coms-content-o'/>,
                content:'显示定制列',
                key:2
            });
        }
        {
            showAddForm && 
            btns.push({
                icon: <i className='icon-coms-Preservation '/>,
                content:'保存',
                key:3
            });
        }
        btns.push({
            icon: <i className='icon-coms-Collection'/>,
            content:'收藏',
            key:4
        });
    	btns.push({
            icon: <i className='icon-coms-help'/>,
            content:'帮助',
            key:5
        });
    	return btns
    }
    onRightMenuClick(key){
        const {actions,comsWeaTable,dataKey,customerId} = this.props;
        const {required} = this.state;
        const tablekey = dataKey ? dataKey.split('_')[0] : 'init';
		const tableNow = comsWeaTable.get(tablekey);
    	const selectedRowKeys = tableNow.get('selectedRowKeys');
       if(key == '0'){
           actions.outResourceAdd({customerId:customerId});
       }
       if(key == '1'){
            actions.outResourceDelete({operation:"delete",id:`${selectedRowKeys.toJS()}`},customerId);
        }
       if(key == '2'){
           actions.setColSetVisible(dataKey,true);
           actions.tableColSet(dataKey,true)
       }
       if(key == '3'){
           actions.saveOutResourceForm({operation:"add",customerId:customerId},required)
       }
       if(key == '4'){
           // actions.setColSetVisible(dataKey,true);
           // actions.tableColSet(true)
       }
   }
   getForm() {
    const { addFormDatas,actions,outResourceOrderFields } = this.props;
    let group = [];
    let viewObj = [];
    addFormDatas.toJS().map(c =>{
        let items = [];
        c.items.map(field => {
            let fit = field.formItemType.toUpperCase();
            if(fit != "BROWSER" && field.viewAttr == "3"){
                viewObj.push(field.domkey[0]);
            }else if(fit == "BROWSER"){
                const bcp = field.browserConditionParam;
                if(bcp.viewAttr == "3"){
                   viewObj.push(field.domkey[0]);
                   actions.saveOutResourceOrderFields({...outResourceOrderFields.toJS(), ...{customid:{name:field.domkey[0],value:field.value}}});
                }  
            }
                items.push({
                    com:(<FormItem
                        label={`${field.label}`}
                        labelCol={{span: `${field.labelcol}`}}
                        wrapperCol={{span: `${field.fieldcol}`}}>
                            { WeaTools.getComponent(field.formItemType, field.browserConditionParam, field.domkey, this.props, field)}
                        </FormItem>),
                    colSpan:1
                })
            });
        group.push(<WeaSearchGroup needTigger={true} title={c.title} showGroup={c.defaultshow} items={items}/>)
    });
    this.setState({required:viewObj})
    return group
}

}

class MyErrorHandler extends React.Component {
    render(){
        const hasErrorMsg = this.props.error && this.props.error!=="";
        return (
            <WeaErrorPage msg={hasErrorMsg?this.props.error:"对不起，该页面异常，请联系管理员！"} />
        );
    }
}

OutResourceList = WeaTools.tryCatch(React, MyErrorHandler, {error: ""})(OutResourceList);

OutResourceList = createForm({
	onFieldsChange(props, fields) {
        props.actions.saveOutResourceOrderFields({...props.outResourceOrderFields.toJS(), ...fields});
    },
	mapPropsToFields(props) {
		return props.outResourceOrderFields.toJS();
  	}
})(OutResourceList);

function mapStateToProps(state) {
    const {crmoutResources,comsWeaTable} = state;
    return  {
        dataKey:crmoutResources.get('dataKey'),
        customerId:crmoutResources.get('customerId'),
        addFormDatas:crmoutResources.get('addFormDatas'),
        showAddForm:crmoutResources.get('showAddForm'),
        outResourceOrderFields:crmoutResources.get('outResourceOrderFields'),
        outResourceParams:crmoutResources.get('outResourceParams'),
        comsWeaTable: comsWeaTable, //绑定整个table
    }
}

function mapDispatchToProps(dispatch) {
    return {
        actions: bindActionCreators({...OutResourceViewAction,...WeaTableAction}, dispatch)
    }
}

export default connect(mapStateToProps, mapDispatchToProps)(OutResourceList);
